import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
// import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  DatePicker,
  // Checkbox,
  // InputNumber,
  // DatePicker,
  // Tooltip,
  // Modal,
  // message,
  // Badge,
  Divider,
  // Popconfirm,
  BackTop,
  // message,
  // notification,
} from 'antd';
import moment from 'moment';
import { isInvalid, getRandomColor, searchFromList, refitCommonData } from '../../../utils/tools';
import StandardTableCustom from '../../../customComponents/StandardTableCustom';
import PageHeaderWrapperCustom from '../../../customComponents/PageHeaderWrapperCustom';
import Ellipsis from '../../../components/Ellipsis';

import styles from './List.less';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ productOrder, global, loading }) => ({
  productOrder,
  global,
  loading: loading.models.productOrder,
}))
@Form.create()
class List extends PureComponent {
  isMountedFlag = false;

  state = {
    dataLoading: true,
    formValues: {},
    customData: {
      count: 0,
      list: [],
      pagination: {},
    },
    startTime: '',
    endTime: '',
    pageNo: 1,
    pageSize: 10,
    selectedDataTableDataRows: [],
  };

  componentDidMount() {
    this.isMountedFlag = true;
    // const { global } = this.props;
    const { pageNo, pageSize } = this.state;

    // this.setState({
    //   rankList: [...rankList, ...global.rankList],
    // });
    // console.dir(global.rankList);

    this.loadData({ pageNo, pageSize });
  }

  componentWillUnmount() {
    this.isMountedFlag = false;
  }

  onDateRangeChange = (dates, dateStrings) => {
    this.setState({
      startTime: dateStrings[0],
      endTime: dateStrings[1],
    });
  };

  cityList = () => {
    const { global } = this.props;
    return refitCommonData(global.cityList, {
      key: -10000,
      name: '不限',
      flag: -10000,
    });
  };

  getCityName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.cityList());
    return item == null ? '未知' : item.name;
  };

  consumerTypeList = () => {
    const { global } = this.props;
    return refitCommonData(global.consumerTypeList, {
      key: -10000,
      name: '不限',
      flag: -10000,
    });
  };

  getConsumerTypeName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.consumerTypeList());
    return item == null ? '未知' : item.name;
  };

  payTypeList = () => {
    const { global } = this.props;
    return refitCommonData(global.payTypeList, {
      key: -10000,
      name: '不限',
      flag: -10000,
    });
  };

  getPayTypeName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.payTypeList());
    return item == null ? '未知' : item.name;
  };

  orderStatusList = () => {
    const { global } = this.props;
    return refitCommonData(global.orderStatusList, {
      key: -10000,
      name: '不限',
      flag: -10000,
    });
  };

  getOrderStatusName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.orderStatusList());
    return item == null ? '未知' : item.name;
  };

  orderTypeList = () => {
    const { global } = this.props;
    return refitCommonData(global.orderTypeList, {
      key: -10000,
      name: '不限',
      flag: -10000,
    });
  };

  getOrderTypeName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.orderTypeList());
    return item == null ? '未知' : item.name;
  };

  orderStatusList = () => {
    const { global } = this.props;
    return refitCommonData(global.orderStatusList, {
      key: -10000,
      name: '不限',
      flag: -10000,
    });
  };

  getOrderStatusName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.orderStatusList());
    return item == null ? '未知' : item.name;
  };

  loadData = params => {
    const { dispatch } = this.props;

    const submitData = params;
    submitData.nowpageindex = submitData.pageNo;
    submitData.pagesize = submitData.pageSize;

    this.setState({ dataLoading: true });

    dispatch({
      type: 'productOrder/list',
      payload: submitData,
    }).then(() => {
      if (this.isMountedFlag) {
        const {
          productOrder: { data },
        } = this.props;

        this.setState({ customData: data, dataLoading: false });
      }
    });
  };

  handleSelectRows = rows => {
    // const list = [];
    // rows.forEach(o => {
    //   list.push(`${o.name}|${o.dataEntityType}`);
    // });
    // const v = list.join();
    // this.setState({
    //   tableList: v,
    // });

    this.setState({
      selectedDataTableDataRows: rows,
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { formValues, startTime, endTime } = this.state;
    // console.dir(pagination);
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
      startTime,
      endTime,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.loadData(params);
  };

  handleFormReset = () => {
    const { form } = this.props;
    const { pageSize } = this.state;

    form.resetFields();
    this.setState({
      formValues: {},
    });

    this.loadData({ pageNo: 1, pageSize });
  };

  refreshGrid = pageNo => {
    const { customData } = this.state;
    const { pagination } = customData;

    const params = {
      pageNo: (pageNo || 1) <= 1 ? 1 : pageNo,
      pageSize: pagination.pageSize,
    };

    this.loadData(params);
  };

  handleSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      this.loadData({
        ...values,
        pageNo: 1,
        pageSize,
      });
    });
  };

  goToDetail = record => {
    const { dispatch } = this.props;
    const { intorderid } = record;
    const location = {
      pathname: `/productOrder/payment/detail/load/${intorderid}/basicInfo`,
    };
    dispatch(routerRedux.push(location));
  };

  renderSimpleForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const { dataLoading } = this.state;

    const orderTypeData = this.orderTypeList();
    const orderTypeOption = [];

    orderTypeData.forEach(item => {
      const { name, flag } = item;
      orderTypeOption.push(
        <Option key={flag} value={flag}>
          {name}
        </Option>
      );
    });

    const orderStatusData = this.orderStatusList();
    const orderStatusOption = [];

    orderStatusData.forEach(item => {
      const { name, flag } = item;
      orderStatusOption.push(
        <Option key={flag} value={flag}>
          {name}
        </Option>
      );
    });

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }} justify="end">
          <Col md={6} sm={24}>
            <FormItem label="站长">
              {getFieldDecorator('sellerName')(<Input placeholder="请输入站长名称" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="订单">
              {getFieldDecorator('serialNumber')(<Input placeholder="请输入订单编号" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="类型">
              {getFieldDecorator('type', {
                rules: [{ required: false, message: '请选择订单类型!' }],
                initialValue: orderTypeData[0].flag,
              })(
                <Select placeholder="请选择订单类型" style={{ width: '100%' }}>
                  {orderTypeOption}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('status', {
                rules: [{ required: false, message: '请选择商品类型!' }],
                initialValue: orderStatusData[0].flag,
              })(
                <Select placeholder="请选择商品类型" style={{ width: '100%' }}>
                  {orderStatusOption}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }} justify="end">
          <Col md={12} sm={24}>
            <FormItem label="时段">
              {getFieldDecorator('dateRange', {
                rules: [{ required: false, message: '请选择商品类型!' }],
              })(
                <RangePicker
                  style={{ width: '100%' }}
                  showTime={{ format: 'HH:mm' }}
                  format="YYYY-MM-DD HH:mm"
                  placeholder={['开始时间', '结束时间']}
                  onChange={this.onDateRangeChange}
                  // onOk={onOk}
                />
              )}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <span className={styles.submitButtons}>
              <Button disabled={dataLoading} type="primary" icon="search" htmlType="submit">
                查询
              </Button>
              <Button
                disabled={dataLoading}
                className={styles.searchButtonMarginLeft}
                icon="reload"
                onClick={this.handleFormReset}
              >
                重置
              </Button>
              <Divider type="vertical" />
              <Button
                disabled={dataLoading}
                type="dashed"
                icon="export"
                onClick={this.showAddNewModal}
              >
                导出
              </Button>
              <Button
                disabled={dataLoading}
                className={styles.searchButtonMarginLeft}
                type="dashed"
                icon="printer"
                onClick={this.showAddNewModal}
              >
                单用户合并打印
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const { loading } = this.props;
    const { customData, selectedDataTableDataRows, dataLoading } = this.state;
    const columns = [
      {
        title: '订单Id',
        dataIndex: 'intorderid',
        width: 80,
        align: 'center',
      },
      {
        title: '城市',
        dataIndex: 'intcityid',
        width: 100,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis
              style={{
                color: getRandomColor(val * 2),
              }}
              tooltip
              lines={1}
            >
              {this.getCityName(val)}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '流水号',
        dataIndex: 'serialNumber',
        width: 100,
        align: 'center',
      },
      {
        title: '用户昵称/收件人',
        dataIndex: 'contact',
        align: 'center',
        render: (val, record) => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val}
              {(record.chvspec || '') === '' ? '' : `(${record.chvspec})`}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '消费者类型',
        dataIndex: 'consumerType',
        width: 120,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis
              style={{
                color: getRandomColor(val + 8),
              }}
              tooltip
              lines={1}
            >
              {this.getConsumerTypeName(val)}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '支付类型',
        dataIndex: 'payType',
        width: 120,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis
              style={{
                color: getRandomColor(val + 14),
              }}
              tooltip
              lines={1}
            >
              {this.getPayTypeName(val)}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '订单状态',
        dataIndex: 'status',
        width: 120,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis
              style={{
                color: getRandomColor(val + 15),
              }}
              tooltip
              lines={1}
            >
              {this.getOrderStatusName(val, '--')}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '总金额',
        dataIndex: 'amount',
        width: 100,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis className={styles.price} tooltip lines={1}>
              ￥{val}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '下单时间',
        dataIndex: 'createTime',
        width: 120,
        align: 'center',
        sorter: false,
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {(val || '') === ''
                ? '--'
                : moment(new Date(val.replace('/', '-'))).format('YYYY-MM-DD')}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '订单类型',
        dataIndex: 'orderType',
        width: 120,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis
              style={{
                color: getRandomColor(val + 6),
              }}
              tooltip
              lines={1}
            >
              {this.getOrderTypeName(val)}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '操作',
        width: 106,
        fixed: 'right',
        align: 'center',
        render: (text, record) => (
          <Fragment>
            <Dropdown.Button
              size="small"
              onClick={() => this.goToDetail(record)}
              overlay={
                <Menu onClick={e => this.handleMenuClick(e, record)}>
                  <Menu.Item key="1">
                    <Icon type="setting" />
                    数据
                  </Menu.Item>
                  <Menu.Item key="2">
                    <Icon type="setting" />
                    下架
                  </Menu.Item>
                  {/* <Menu.Item key="2">
                    <Icon type={record.status === 2 ? 'minus-circle' : 'check-circle'} />
                    {record.status === 2 ? '禁用' : '启用'}
                  </Menu.Item> */}
                </Menu>
              }
            >
              <Icon type="read" />
              查看
            </Dropdown.Button>
          </Fragment>
        ),
      },
    ];

    // const rowSelection = {
    //   onChange: (selectedRowKeys, selectedRows) => {
    //     console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    //   },
    //   getCheckboxProps: record => ({
    //     disabled: record.name === 'Disabled User', // Column configuration not to be checked
    //     name: record.name,
    //   }),
    // };

    return (
      <PageHeaderWrapperCustom title="支付订单列表">
        <Card bordered={false} className={styles.listContainor}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTableCustom
              loading={loading || dataLoading}
              data={customData}
              showSelect
              selectedRows={selectedDataTableDataRows}
              columns={columns}
              scroll={{ x: 1340 }}
              // expandedRowRender={record => (
              //   <div>
              //     <p>
              //       <span className="bold">商品名称：</span>
              //       <span>{`${record.name}（ 编码：${record.customCode || '无'} ）`}</span>
              //     </p>
              //     <p>
              //       <span className="bold">简介描述：</span>
              //       <span>{record.description}</span>
              //     </p>
              //     <Divider />
              //     <p>
              //       <span className="bold">其他信息：</span>
              //       <span>{`发布于 ${record.dtmintime}，最后更新于 ${record.updateTime}。`}</span>
              //     </p>
              //   </div>
              // )}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <BackTop />
      </PageHeaderWrapperCustom>
    );
  }
}

export default List;
